package com.nullpointer.xchatfinal.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.nullpointer.xchatfinal.R;
import com.nullpointer.xchatfinal.adapter.SelectFriendAdapter;
import com.nullpointer.xchatfinal.object.SelectFriend;
import com.nullpointer.xchatfinal.object.User;
import com.nullpointer.xchatfinal.utils.Common;
import com.nullpointer.xchatfinal.utils.DataManager;
import com.nullpointer.xchatfinal.utils.KiraGameLog;
import com.nullpointer.xchatfinal.utils.Utils;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.model.QBDialog;
import com.quickblox.core.QBEntityCallbackImpl;
import com.quickblox.core.request.QBPagedRequestBuilder;
import com.quickblox.core.request.QBRequestGetBuilder;
import com.quickblox.customobjects.QBCustomObjects;
import com.quickblox.customobjects.model.QBCustomObject;
import com.quickblox.users.QBUsers;
import com.quickblox.users.model.QBUser;

public class ChooseFriendDialogFragment extends DialogFragment {
	private static final String ROOM_JID = "ROOM_JID";
	private static final String CHECKED_USER = "CHECKED_USER";
	private CheckBox cbSellectAll;
	private ListView lvFriend;
	private LinearLayout llInfo;
	private ProgressBar pbLoading;
	private TextView tvInfo;
	private Button btAdd;
	private Button btCancel;
	private OnChooseFriendDialogFragment listener;
	private List<SelectFriend> data = new ArrayList<SelectFriend>();
	private SelectFriendAdapter adapter;
	private String roomJID;
	private List<String> checkedUserID;

	public static ChooseFriendDialogFragment newInstance(String roomJID,
			ArrayList<String> checkedUserID) {
		ChooseFriendDialogFragment f = new ChooseFriendDialogFragment();
		Bundle args = new Bundle();
		args.putString(ROOM_JID, roomJID);
		if (checkedUserID == null) {
			args.putStringArrayList(CHECKED_USER, new ArrayList<String>());
		} else {
			args.putStringArrayList(CHECKED_USER, checkedUserID);
		}

		f.setArguments(args);
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		roomJID = getArguments().getString(ROOM_JID);
		checkedUserID = getArguments().getStringArrayList(CHECKED_USER);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater
				.inflate(R.layout.fragment_choose_friend, container);
		findViewIds(view);
		init();
		setEvent();
		return view;
	}

	private void init() {
		getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
		adapter = new SelectFriendAdapter(getActivity(), data);
		lvFriend.setAdapter(adapter);
		getFriendsUser();
	}

	@Override
	public void onStart() {
		super.onStart();
		Dialog dialog = getDialog();
		if (dialog != null) {
			dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
					ViewGroup.LayoutParams.MATCH_PARENT);
			// dialog.getWindow().setBackgroundDrawable(
			// new ColorDrawable(Color.TRANSPARENT));

		}
	}

	private void getFriendsUser() {
		showInfo("loading...", true);
		QBRequestGetBuilder requestBuilder = new QBRequestGetBuilder();
		requestBuilder.setPagesLimit(1);
		requestBuilder.eq(Common.FriendsObject.USER_ID, DataManager
				.getInstance(getActivity()).getCurrentUser().getUserID());

		QBCustomObjects.getObjects(Common.FriendsObject.FRIENDS_CLASS,
				requestBuilder,
				new QBEntityCallbackImpl<ArrayList<QBCustomObject>>() {

					@Override
					public void onSuccess(
							ArrayList<QBCustomObject> customObjects,
							Bundle params) {
						KiraGameLog.d(">>> custom objects: " + customObjects);
						if (customObjects.size() == 0) {
							// No friend
							showNoFriends();
						} else {
							QBCustomObject object = customObjects.get(0);
							Object frObject = object.getFields().get(
									Common.FriendsObject.LIST_FRIENDS);
							if (frObject == null) {
								// No friend
								showNoFriends();
								return;
							}
							String friends = frObject.toString();
							if (friends != null) {
								String[] array = friends.split("/");
								Set<String> list = new HashSet<>();
								Collections.addAll(list, array);
								if (roomJID != null) {
									getMemberInRoom(roomJID, list);
								} else {
									getUsersByIds(list);
								}

							} else {
								// No friend
								showNoFriends();
							}

						}

					}

					@Override
					public void onError(List<String> errors) {
						KiraGameLog.d("getReportUser error " + errors);
						hideInfo();
					}
				});

	}

	protected void getMemberInRoom(String roomJID, final Set<String> userIDs) {
		QBRequestGetBuilder requestBuilder = new QBRequestGetBuilder();
		requestBuilder.setPagesLimit(1);
		requestBuilder.addParameter("xmpp_room_jid", roomJID);

		QBChatService.getChatDialogs(null, requestBuilder,
				new QBEntityCallbackImpl<ArrayList<QBDialog>>() {
					@Override
					public void onSuccess(ArrayList<QBDialog> dialogs,
							Bundle args) {
						KiraGameLog.d("get dialogs: " + dialogs);
						QBDialog qbDialog = dialogs.get(0);
						for (Integer userID : qbDialog.getOccupants()) {
							String id = String.valueOf(userID);
							if (userIDs.contains(id)) {
								userIDs.remove(id);
							}
						}
						getUsersByIds(userIDs);
					}

					@Override
					public void onError(List<String> errors) {
						getUsersByIds(userIDs);
					}
				});
	}

	protected void showNoFriends() {
		showInfo("You have no friends in contact list", false);
	}

	protected void getUsersByIds(Set<String> usersIds) {
		QBPagedRequestBuilder pagedRequestBuilder = new QBPagedRequestBuilder();
		pagedRequestBuilder.setPage(1);
		pagedRequestBuilder.setPerPage(100);
		Set<Integer> listFriendIds = new HashSet<Integer>();
		for (String string : usersIds) {
			listFriendIds.add(Integer.parseInt(string));
		}

		QBUsers.getUsersByIDs(listFriendIds, pagedRequestBuilder,
				new QBEntityCallbackImpl<ArrayList<QBUser>>() {
					@Override
					public void onSuccess(ArrayList<QBUser> users, Bundle params) {
						if (users == null || users.size() == 0) {
							hideInfo();
						} else {
							for (QBUser user : users) {
								User mUser = Utils.convertQBUserToUser(user);
								SelectFriend selectFriend = new SelectFriend();
								String userID = String.valueOf(user.getId());
								selectFriend.setUserID(userID);
								selectFriend.setUserName(user.getFullName());
								selectFriend.setAvatarID(mUser.getUserInfo().getAvatarID());
								if (checkedUserID.contains(userID)) {
									selectFriend.setChecked(true);
								} else {
									selectFriend.setChecked(false);
								}
								data.add(selectFriend);
							}
							adapter.notifyDataSetChanged();
							hideInfo();
						}
					}

					@Override
					public void onError(List<String> errors) {
						KiraGameLog.d(">>> get friend user error:" + errors);
						hideInfo();
					}

				});
	}

	private void setEvent() {
		btAdd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (listener != null) {
					List<SelectFriend> users = new ArrayList<SelectFriend>();
					for (SelectFriend user : data) {
						if (user.isChecked()) {
							users.add(user);
						}
					}
					listener.onChooseFriend(users);
				}
				dismiss();
			}
		});
		btCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (listener != null) {
					listener.onCancel();
				}
				dismiss();
			}
		});

		cbSellectAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				for (SelectFriend user : data) {
					user.setChecked(isChecked);
				}
				adapter.notifyDataSetChanged();
			}
		});
	}

	public void showInfo(String messgae, boolean isShowProgessbar) {
		llInfo.setVisibility(View.VISIBLE);
		tvInfo.setText(messgae);
		if (isShowProgessbar) {
			pbLoading.setVisibility(View.VISIBLE);
		} else {
			pbLoading.setVisibility(View.GONE);
		}
	}

	public void hideInfo() {
		llInfo.setVisibility(View.GONE);
	}

	private void findViewIds(View view) {
		cbSellectAll = (CheckBox) view.findViewById(R.id.cb_sellect_all);
		lvFriend = (ListView) view.findViewById(R.id.lv_friend);
		btAdd = (Button) view.findViewById(R.id.bt_add);
		btCancel = (Button) view.findViewById(R.id.bt_cancel);
		llInfo = (LinearLayout) view.findViewById(R.id.ll_info);
		pbLoading = (ProgressBar) view.findViewById(R.id.pb_loading);
		tvInfo = (TextView) view.findViewById(R.id.tv_info);
	}

	public void setOnChooseFriendDialogFragment(
			OnChooseFriendDialogFragment listener) {
		this.listener = listener;
	}

	public interface OnChooseFriendDialogFragment {
		void onCancel();

		void onChooseFriend(List<SelectFriend> userIDs);
	}
}
